package com.oocl.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

@WebServlet("/local/*")
public class LocalResourcesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = Logger.getLogger(LocalResourcesServlet.class);
	
	private final String LOCAL_FOLDER_PATH = System.getenv("CATALINA_HOME") + File.separator + "O2OFile";

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String requestUri = request.getRequestURI();
		String regex = "^\\" + request.getContextPath() + "\\/local(\\/.*)";
		Matcher matcher = Pattern.compile(regex).matcher(requestUri);
		matcher.matches();
		String path = LOCAL_FOLDER_PATH + matcher.group(1);
		LOGGER.info("path:"+path);
		try {
			FileInputStream fis = new FileInputStream(path);
			OutputStream out = response.getOutputStream();
			IOUtils.copy(fis, out);
			fis.close();
			out.close();
		} catch (FileNotFoundException e) {
			LOGGER.error(e.getMessage());
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
